package fragments;

import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseFragment;
import com.example.administrator.newxlmedical.R;
import com.example.administrator.newxlmedical.StartActivity;

import java.util.ArrayList;
import java.util.List;

import adapters.HospitalRegisterDepartAdapter;
import beans.AllDepts;
import beans.AllEmployee;
import beans.HospitalDepartBean;
import beans.HospitalNameBean;
import beans.HospitalRegisterDepartBean;
import beans.PostBean;
import beans.RegisterInfoBean;
import beans.UserInfoBean;
import beans.XLKJResult;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import dialogs.HospitalRegisterInfoDialog;
import interfaces.MyItemClickListener;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import singleton.SingletonClass;
import utils.MD5;
import utils.ObjectSaveUtil;
import utils.ScreenUtils;
import utils.TimeUtil;
import utils.ToastUtil;

/**
 * A simple {@link Fragment} subclass.
 */
public class HospitalRegisterFragment extends BaseFragment {

    @BindView(R.id.et_hospital_register_code)
    EditText etCode;
    @BindView(R.id.et_hospital_register_department)
    EditText etDepartment;
    @BindView(R.id.tv_hospital_register_register)
    TextView tvRegister;
    @BindView(R.id.rv_hospital_register)
    RecyclerView recyclerView;
    Unbinder unbinder;
    @BindView(R.id.et_hospital_register_password)
    EditText etPassword;
    @BindView(R.id.iv_hospital_rigister_back)
    ImageView ivBack;

    private HospitalRegisterDepartAdapter adapter;
    private List<HospitalRegisterDepartBean> list = new ArrayList<>();
    private MyHandler allhandler;
    private RegisterInfoBean bean;
    private int count;
    private ImageView ivIcon;
    private int type;
    private boolean isSearch = true;
    private List<AllDepts> allDepts = new ArrayList<>();

    public HospitalRegisterFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Bundle arguments = getArguments();
        type = arguments.getInt("type");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_hospital_register, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        allhandler = SingletonClass.getSingleton(MyHandler.class);
        bean = (RegisterInfoBean) getArguments().getSerializable(Constants.HOSPITAL_REGISTER_FRAGMENT);

        List<AllDepts> result = (List<AllDepts>) ObjectSaveUtil.readObject(mContext, Constants.ALL_DEPT, Constants.ALL_DEPT);

        if (result != null && result.size() != 0) {
            Log.e(TAG, "initView: result");
            allDepts.addAll(result);
        }

        ivIcon = (ImageView) view.findViewById(R.id.imageView);
        if (bean.getRegisterRole() == Constants.ROLE_MANAGE) {
            ivIcon.setImageResource(R.mipmap.role_manage);
        } else if (bean.getRegisterRole() == Constants.ROLE_NURSE) {
            ivIcon.setImageResource(R.mipmap.role_nurse);
        } else if (bean.getRegisterRole() == Constants.ROLE_HEAD_NURSE) {
            ivIcon.setImageResource(R.mipmap.role_head_nurse);
        } else {
            ivIcon.setImageResource(R.mipmap.role_supplier);
        }

        adapter = new HospitalRegisterDepartAdapter(mContext, list);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);

        etDepartment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (isSearch) {
                    if (!TextUtils.isEmpty(s.toString())) {
                        String text = s.toString();
                        list.clear();
                        if (Constants.IS_FUYI) {
                            getDepartment(text, 1);
                        } else {
                            getDepts(text, 1);  //协和医院
                        }
                    } else {
                        recyclerView.setVisibility(View.GONE);
                    }
                } else {
                    isSearch = true;
                }
                Log.e(TAG, "onTextChanged: ");

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /*
        协和医院
     */
    private void getDepts(String text, int type) {
        Log.e(TAG, "getDepts: " + allDepts.size());
        if (type == 1) {
            for (int i = 0; i < allDepts.size(); i++) {
                AllDepts allDepts = this.allDepts.get(i);
                String dept = allDepts.getKsmc();
                String code = allDepts.getKsdm();
                if (dept.contains(text)) {
                    HospitalRegisterDepartBean bean = new HospitalRegisterDepartBean();
                    bean.setDepartment(dept);
                    bean.setDeptCode(code);
                    list.add(bean);
//                    Log.e(TAG, "list: " + dept);
                }
            }
            adapter.notifyDataSetChanged();
            recyclerView.setVisibility(View.VISIBLE);
        } else {
            int count = 0;
            for (int i = 0; i < allDepts.size(); i++) {
                AllDepts allDepts = this.allDepts.get(i);
                String dept = allDepts.getKsmc();
                if (dept.contains(text)) {
                    count++;
                    sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                    break;
                }
            }
            if (count == 0) {
                ToastUtil.showToast(mContext, "您输入的科室有误");
            }
        }
    }

    private void getUserInfo(String code) {
        GetRetrofit.getInstance3().getHospitalUserInfo(code)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<XLKJResult<AllEmployee>>() {
                    @Override
                    public void call(XLKJResult<AllEmployee> allEmployeeXLKJResult) {

                        if (allEmployeeXLKJResult.getResultCode() == 100) {
                            List<AllEmployee> result = allEmployeeXLKJResult.getResult();
                            if (result != null && result.size() != 0) {
                                AllEmployee allEmployee = result.get(0);
                                bean.setName(allEmployee.getYGXM());
//                                bean.setWorkKind(allEmployee.get());
                                if (!TextUtils.isEmpty(etPassword.getText().toString())) {
                                    bean.setPassword(MD5.md5(etPassword.getText().toString()));
                                }
                                sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                            }
                        } else {
                            ToastUtil.showToast(mContext, allEmployeeXLKJResult.getMsg());
                        }

                    }
                }, new MyAction1());
    }

    private void checkName(String UCode){
        GetRetrofit.getInstance().getUserInfo(NetAddress.token,NetAddress.machineCode,"select * from UserInfo where UCode = '" + UCode + "'")
                .enqueue(new Callback<ArrayList<UserInfoBean>>() {
                    @Override
                    public void onResponse(Call<ArrayList<UserInfoBean>> call, Response<ArrayList<UserInfoBean>> response) {

                        ArrayList<UserInfoBean> body = response.body();
                        if (body != null && body.size() != 0){
                            ToastUtil.showToast(getContext(),"此员工编号已被注册！");
                        }else {
                            if (Constants.IS_FUYI) {
                                getName(etCode.getText().toString());
                            } else {
                                getUserInfo(etCode.getText().toString());
                                //查询科室
                                getDepts(etDepartment.getText().toString(), 2);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ArrayList<UserInfoBean>> call, Throwable t) {

                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void setListener() {
        super.setListener();
        adapter.setItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                String department = list.get(position).getDepartment();
                Log.e(TAG, "onItemClick: " + list.get(position).getDeptCode());
                bean.setDepartment(department);
                isSearch = false;
                etDepartment.setText(department);
                recyclerView.setVisibility(View.GONE);
                etDepartment.setSelection(department.length());
                list.clear();
                ScreenUtils.closeKeybord(etDepartment, mContext);
            }
        });
    }

    @OnClick({R.id.tv_hospital_register_register, R.id.iv_hospital_rigister_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_hospital_register_register:
                register();
                break;
            case R.id.iv_hospital_rigister_back:
                allhandler.sendEmptyMessage(HandlerConstant.REGISTER_SUCCESS_FRAGMENT_SURE);
                break;
        }

    }

    private void register() {
        count = 0;
        //员工编号没有注册过,则去医院数据库查看员工编码

        if (TextUtils.isEmpty(etCode.getText().toString().trim()) && etCode.getText().toString().trim().length() == 4){
            ToastUtil.showToast(getContext(),"员工编号不能为空");
            return;
        }

        if (TextUtils.isEmpty(etDepartment.getText().toString().trim())){
            ToastUtil.showToast(getContext(),"科室不能为空");
            return;
        }

        checkName(etCode.getText().toString());

    }

    //1代表按搜索按钮,进行模糊查询,2是点击注册时,保证科室正确
    private void getDepartment(final String office, final int type) {
        GetRetrofit.getInstance2().getHospitalDepartment(office).subscribeOn(Schedulers.io()).groupBy(new Func1<List<HospitalDepartBean>, Boolean>() {
            @Override
            public Boolean call(List<HospitalDepartBean> hospitalDepartBeen) {
                return hospitalDepartBeen == null ? false : hospitalDepartBeen.size() > 0;

            }
        }).observeOn(AndroidSchedulers.mainThread()).flatMap(new Func1<GroupedObservable<Boolean, List<HospitalDepartBean>>, Observable<HospitalDepartBean>>() {
            @Override
            public Observable<HospitalDepartBean> call(GroupedObservable<Boolean, List<HospitalDepartBean>> booleanListGroupedObservable) {
                if (booleanListGroupedObservable.getKey()) {
                    return booleanListGroupedObservable.subscribeOn(Schedulers.io()).flatMap(new Func1<List<HospitalDepartBean>, Observable<HospitalDepartBean>>() {
                        @Override
                        public Observable<HospitalDepartBean> call(List<HospitalDepartBean> hospitalDepartBeen) {
                            return Observable.from(hospitalDepartBeen).doOnNext(new Action1<HospitalDepartBean>() {
                                @Override
                                public void call(HospitalDepartBean hospitalDepartBean) {
                                    if (type == 1) {
                                        HospitalRegisterDepartBean bean = new HospitalRegisterDepartBean();
                                        bean.setDepartment(hospitalDepartBean.get_dept_name());
                                        bean.setDeptCode(hospitalDepartBean.get_dept_code());
                                        list.add(bean);
                                    }
                                }
                            }).last().observeOn(AndroidSchedulers.mainThread());
                        }
                    });
                } else {
                    ToastUtil.showToast(mContext, "您输入的科室有误");
                    return null;
                }
            }
        }).subscribe(new Action1<HospitalDepartBean>() {
            @Override
            public void call(HospitalDepartBean hospitalDepartBean) {
                if (type == 1) {
                    recyclerView.setVisibility(View.VISIBLE);
                    adapter.notifyDataSetChanged();
                } else {
//                    bean.setDepartment(hospitalDepartBean.get_dept_name());
                    sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                }
            }
        }, new MyAction1());
    }

    //根据员工编码从医院数据库查询员工姓名
    private void getName(String ucode) {
        GetRetrofit.getInstance2().getHospitalName(ucode).subscribeOn(Schedulers.io()).groupBy(new Func1<List<HospitalNameBean>, Boolean>() {
            @Override
            public Boolean call(List<HospitalNameBean> hospitalNameBeen) {
                return hospitalNameBeen == null ? false : hospitalNameBeen.size() > 0;
            }
        }).observeOn(AndroidSchedulers.mainThread()).flatMap(new Func1<GroupedObservable<Boolean, List<HospitalNameBean>>, Observable<HospitalNameBean>>() {
            @Override
            public Observable<HospitalNameBean> call(GroupedObservable<Boolean, List<HospitalNameBean>> booleanListGroupedObservable) {
                if (booleanListGroupedObservable.getKey()) {
                    return booleanListGroupedObservable.subscribeOn(Schedulers.io()).flatMap(new Func1<List<HospitalNameBean>, Observable<HospitalNameBean>>() {
                        @Override
                        public Observable<HospitalNameBean> call(List<HospitalNameBean> hospitalNameBeen) {
                            return Observable.from(hospitalNameBeen);
                        }
                    });
                } else {
                    ToastUtil.showToast(mContext, "您输入的员工编码有误");
                    return null;
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<HospitalNameBean>() {
            @Override
            public void call(HospitalNameBean hospitalNameBean) {
                bean.setName(hospitalNameBean.get_name());
                bean.setWorkKind(hospitalNameBean.get_work_kind());
                if (!TextUtils.isEmpty(etPassword.getText().toString())) {
                    bean.setPassword(MD5.md5(etPassword.getText().toString()));
                }
                sendEmptyMessage(HandlerConstant.FINISH_NETWORK);

                getDepartment(etDepartment.getText().toString(), 2);
            }
        }, new MyAction1());
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case HandlerConstant.FINISH_NETWORK:
                count++;
                if (count == 2) {
                    count = 0;
                    bean.setCode(etCode.getText().toString());
                    new HospitalRegisterInfoDialog(mContext, R.style.dialog, bean, new HospitalRegisterInfoDialog.OnClickListener() {
                        @Override
                        public void onSureClickListener(HospitalRegisterInfoDialog dialog) {
                            postUser();

                            Message message = allhandler.obtainMessage();
                            message.obj = bean;
                            message.what = HandlerConstant.REGISTER_TYPE;
                            allhandler.sendMessage(message);
                            dialog.dismiss();
                        }
                    }).show();
                }
                break;
        }
    }

    private void postUser() {

        UserInfoBean userInfoBean = new UserInfoBean();
        userInfoBean.setName(bean.getName());
        userInfoBean.setUCode(bean.getCode());
        userInfoBean.setSubTime(TimeUtil.getMillisecondDate());
        userInfoBean.setDepartment(bean.getDepartment());
        userInfoBean.setRoleInfoId(bean.getRegisterRole());
        if (!TextUtils.isEmpty(bean.getPassword())) {
            userInfoBean.setPassword(bean.getPassword());
        }
        userInfoBean.setWorkKind(bean.getWorkKind());
        userInfoBean.setEnable(true);
        userInfoBean.setChangeTime(TimeUtil.getMillisecondDate());

        GetRetrofit.getInstance().postUserInfo(NetAddress.token, NetAddress.machineCode, userInfoBean)
                .enqueue(new Callback<PostBean>() {
                    @Override
                    public void onResponse(Call<PostBean> call, Response<PostBean> response) {
                        allhandler.sendEmptyMessage(HandlerConstant.REFRESH_NET); // 管理页面刷新数据
                    }

                    @Override
                    public void onFailure(Call<PostBean> call, Throwable t) {
                    }
                });

    }
}
